﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TransactionRepository.cs" company="Concept Architecture">
//   (c) 2010 Muhammad Umer Farooq
// </copyright>
// <summary>
//   Defines the <seealso cref="Hisaab.Data.TransactionRepository" /> type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Hisaab.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data.Objects;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Linq.Expressions;
    using Entities;
    using Filters;
    using Interfaces;

    using Microsoft.Practices.ServiceLocation;

    /// <summary>
    /// Defines the <seealso cref="Hisaab.Data.TransactionRepository"/> type.
    /// </summary>
    public class TransactionRepository : ITransactionRepository
    {
        /// <summary>
        /// Databse instance to use
        /// </summary>
        private readonly IDatabase _database;

        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionRepository"/> class.
        /// </summary>
        public TransactionRepository()
            : this(ServiceLocator.Current.GetInstance<IDatabase>())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransactionRepository"/> class.
        /// </summary>
        /// <param name="database">The database.</param>
        public TransactionRepository(IDatabase database)
        {
            Contract.Requires<ArgumentNullException>(database != null);
            _database = database;
        }

        /// <summary>
        /// Gets the filtered.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of filtered items</returns>
        public IQueryable<Transaction> Query(Transaction filter, int? pageNo, int? pageSize)
        {
            return _database.Transactions
                .Filter(filter)
                .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Queries the specified filter.
        /// </summary>
        /// <param name="filter">The filter.</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>List of filtered items</returns>
        public IQueryable<Transaction> Filter(Expression<Func<Transaction, bool>> filter, int? pageNo, int? pageSize)
        {
            return _database.Transactions
                .Where(filter)
                .Page(pageNo, pageSize);
        }

        /// <summary>
        /// Finds the by id.
        /// </summary>
        /// <param name="id">The id of entity</param>
        /// <returns>Entity matching by id</returns>
        public Transaction FindById(int id)
        {
            return _database.Transactions
                .Filter(new Transaction { Id = id })
                .FirstOrDefault();
        }

        /// <summary>
        /// Adds the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>Id of transaction added</returns>
        public int Add(Transaction entity)
        {
            var tagList = new List<Tag>();
            foreach (var tag in entity.Tags)
            {
                var exisitingTag = _database.Tags.Where(x => x.Id == tag.Id).FirstOrDefault();
                if (exisitingTag != null)
                {
                    tagList.Add(exisitingTag);
                }
            }

            entity.Tags = tagList;

            _database.Transactions.AddObject(entity);
            _database.SaveChanges();
            _database.Refresh(RefreshMode.StoreWins, _database.Transactions);
            return entity.Id;
        }

        /// <summary>
        /// Updates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Update(Transaction entity)
        {
            var previousEntity = _database.Transactions.Filter(new Transaction { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                previousEntity.Title = entity.Title;
                previousEntity.Account = entity.Account;
                previousEntity.Amount = entity.Amount;
                previousEntity.Details = entity.Details;
                previousEntity.Date = entity.Date;
                previousEntity.Tags.Clear();
                foreach (var tag in entity.Tags)
                {
                    var exisitingTag = _database.Tags.Where(x => x.Id == tag.Id).FirstOrDefault();
                    if (exisitingTag != null)
                    {
                        previousEntity.Tags.Add(exisitingTag);
                    }
                }
            }

            _database.SaveChanges();
            _database.Refresh(RefreshMode.StoreWins, _database.Transactions);
        }

        /// <summary>
        /// Deletes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public void Delete(Transaction entity)
        {
            var previousEntity = _database.Transactions.Filter(new Transaction { Id = entity.Id }).FirstOrDefault();

            if (previousEntity != null)
            {
                _database.Transactions.DeleteObject(previousEntity);
            }

            _database.SaveChanges();
            _database.Refresh(RefreshMode.StoreWins, _database.Transactions);
        }

        /// <summary>
        /// Queries the between dates.
        /// </summary>
        /// <param name="filter">The transaction.</param>
        /// <param name="startDate">Start date for query</param>
        /// <param name="endDate">End date for query</param>
        /// <param name="sortBy">The sort by.</param>
        /// <param name="orderBy">The order by.</param>
        /// <param name="additionalFilter">The additional filter.</param>
        /// <returns>
        /// List of transaction
        /// </returns>
        public IEnumerable<Transaction> QueryBetweenDates(Transaction filter, DateTime startDate, DateTime endDate, SortByType sortBy, OrderByType orderBy, Func<Transaction, bool> additionalFilter)
        {
            return _database.Transactions
                .BetweenDates(filter, startDate, endDate)
                .Where(additionalFilter ?? (x => true)).AsQueryable()
                .OrderTransactions(sortBy, orderBy)
                .ToList();
        }

        /// <summary>
        /// Queries the between dates by tag.
        /// </summary>
        /// <param name="tagId">The tag id.</param>
        /// <param name="startDate">The start date.</param>
        /// <param name="endDate">The end date.</param>
        /// <param name="sortBy">The sort by.</param>
        /// <param name="orderBy">The order by.</param>
        /// <param name="additionalFilter">The func.</param>
        /// <returns>List of transaction</returns>
        public IEnumerable<Transaction> QueryBetweenDatesByTag(int tagId, DateTime startDate, DateTime endDate, SortByType sortBy, OrderByType orderBy, Func<Transaction, bool> additionalFilter)
        {
            return _database.Transactions
                .FilterByTag(tagId)
                .BetweenDates(startDate, endDate)
                .Where(additionalFilter ?? (x => true)).AsQueryable()
                .OrderTransactions(sortBy, orderBy)
                .ToList();
        }
    }
}